﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using iTextSharp.text.pdf;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace P3.Modules.SharePoint.PDF2Lib.Pdf2LibSaveProperties
{
    /// <summary>
    /// Listenelementereignisse
    /// </summary>
    public class Pdf2LibSaveProperties : SPItemEventReceiver
    {

        /// <summary>
        /// Ein Element wurde hinzugefügt.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            if (properties.ListItem.File.Name.ToLower().EndsWith(".pdf"))
            {
                saveproperties2Library(properties);
            }

            base.ItemAdded(properties);
        }

        private void saveproperties2Library(SPItemEventProperties properties)
        {
            string settingsValue;

            loadSettings(properties.Web, properties.ListId, out settingsValue);

            string[] pdfFields_LibCol_Pairs = settingsValue.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

            SPList library = properties.List;
            Hashtable mappings = new Hashtable();
            string[] pdfFieldsArray = new string[pdfFields_LibCol_Pairs.Length];
            string[] libraryColumnsArray = new string[pdfFields_LibCol_Pairs.Length];

            for (int k = 0; k < pdfFields_LibCol_Pairs.Length; k++)
            {
                string[] keyValPair = pdfFields_LibCol_Pairs[k].Split(new string[] { " : " }, StringSplitOptions.RemoveEmptyEntries);

                pdfFieldsArray[k] = keyValPair[0];
                libraryColumnsArray[k] = keyValPair[1];
            }

            SPField tmpField;
            object fieldValue = null;
            DateTime bufDateTime;
            bool bufBool;
            if (pdfFieldsArray.Length > 0)
            {
                PdfReader pdfReader = new PdfReader(properties.ListItem.File.OpenBinary());

                for (int i = 0; i < pdfFieldsArray.Length; i++)
                {
                    try
                    {
                        tmpField = library.Fields.GetField(libraryColumnsArray[i]);
                        fieldValue = pdfReader.AcroFields.GetField(pdfFieldsArray[i]);
                        if (!string.IsNullOrEmpty(fieldValue as string) || (tmpField.Type.Equals(SPFieldType.Boolean)))
                        {
                            switch (tmpField.Type)
                            {
                                case SPFieldType.DateTime:
                                    {
                                        if (!(DateTime.TryParse(fieldValue.ToString(), out bufDateTime)))
                                        {
                                            try
                                            {
                                                properties.ListItem[tmpField.Id] = fieldValue.ToString();
                                            }
                                            catch (Exception)
                                            {
                                            }
                                        }
                                        else
                                        {
                                            properties.ListItem[tmpField.Id] = bufDateTime;
                                        }
                                        break;
                                    }
                                case SPFieldType.Boolean:
                                    {
                                        if (!(Boolean.TryParse(fieldValue.ToString(), out bufBool)))
                                        {
                                            try
                                            {
                                                if ("ja".Equals(fieldValue.ToString().Trim().ToLower()))
                                                    fieldValue = "true";
                                                if ("nein".Equals(fieldValue.ToString().Trim().ToLower()))
                                                    fieldValue = "false";
                                                if ("yes".Equals(fieldValue.ToString().Trim().ToLower()))
                                                    fieldValue = "true";
                                                if ("no".Equals(fieldValue.ToString().Trim().ToLower()))
                                                    fieldValue = "false";
                                                if ("".Equals(fieldValue.ToString().Trim().ToLower()))
                                                    fieldValue = "false";
                                                properties.ListItem[tmpField.Id] = fieldValue.ToString();
                                            }
                                            catch (Exception)
                                            {
                                            }
                                        }
                                        else
                                        {
                                            properties.ListItem[tmpField.Id] = bufBool;
                                        }
                                        break;
                                    }
                                default:
                                    {
                                        properties.ListItem[tmpField.Id] = fieldValue;
                                        break;
                                    }
                            }
                        }
                        else
                            properties.ListItem[tmpField.Id] = null;
                    }
                    catch (Exception)
                    {
                    }
                }
                try
                {
                    EventFiringEnabled = false;
                    try
                    {
                        properties.ListItem.SystemUpdate(false);
                    }
                    catch (Exception ex)
                    {

                    }
                }
                finally
                {
                    EventFiringEnabled = true;
                }

            }
        }

        public static void loadSettings(SPWeb web, Guid library, out string settingsValue)
        {
            string libraryString = library.ToString();
            settingsValue = "";
            if (web.Properties.ContainsKey(libraryString))
            {
                string settingsString = web.Properties[libraryString];
                if (!(string.IsNullOrEmpty(settingsString)))
                {
                    settingsValue = settingsString;
                }
            }
        }

        /// <summary>
        /// Ein Element wurde aktualisiert.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            if (properties.ListItem.File.Name.ToLower().EndsWith(".pdf"))
            {
                saveproperties2Library(properties);
            }
            base.ItemUpdated(properties);
        }

    }
}
